//
//  KSBaseFilterV.swift
//  ANOA
//
//  Created by 邱仙凯 on 2024/12/16.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
struct BannerData {
    var param:String?
    var title:String?
    var content:String?
    
}
class KSBaseFilterV:UIViewController,UITableViewDelegate,UITableViewDataSource,DateWidgetable {
  
    // 把完整模板丢进来
    var templateFilter = [TemplateModel]() {
        didSet {
            self.fContentArr = temp2Fcontent(showTFilter: templateFilter.filter{$0.isFilterShow == "1"})
         }
    }
    // 赋值模板并处理 数据源
    func assignTemplateFilterAndConfigFcontentArr(_ tf:[TemplateModel]) {
        templateFilter =  tf
    }
    
    // 全部 显示的  过滤条件
     var fContentArr =  [SlideContent]()
     var ori_arr =  [SlideContent]()

    var rootTemp = MainTempModel(JSON:["":""])!
    
    var page = 1
    var default_page = 1
    var default_size = KSGlobal.pageSize
    var filterDic = [String:String]()
    var tableAndConfirmV:UIView!
    var topCover:UIView = {
        var v = UIView()
        v.isUserInteractionEnabled = true
        v.backgroundColor = .clear
        return v
    }()
    var bottomCover:UIView = {
       var v = UIView()
        v.layer.masksToBounds = true
        v.isUserInteractionEnabled = true
        v.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        return v
    }()
 
    var resultClosure:((String)->())?
 
    var confirmClosure:(([SlideContent])->())? // 选中后的返回，直接取值使用
     var tableView:UITableView?
 
    var resetClosure:(()->())? // 通知外面，重置了
     var appearance: KSFilterAppearance!
    var closeClosure:(()->())? // 通 

    lazy var confirm:UIButton = {
        let v:UIButton = UIButton()
        v.backgroundColor = UIColor(kshex: "#4972F9")
        v.setTitle("查询", for: .normal)
        v.setTitleColor(.white, for: .normal)
        v.layer.masksToBounds = true
        return v
    }()
    lazy var reset:UIButton = {
        let v:UIButton = UIButton()
        v.layer.borderWidth = 1
        v.layer.borderColor = UIColor(kshex: "#8991B0").cgColor
        v.setTitle("重置", for: .normal)
        v.setTitleColor(UIColor(kshex: "#8991B0"), for: .normal)
        v.layer.masksToBounds = true
        return v
    }()
    var startY:CGFloat = 0
    init(startY: CGFloat,appearance: KSFilterAppearance? = nil,arr:[SlideContent] = []) {
        self.fContentArr = arr
        self.ori_arr = arr
        self.startY = startY
        if appearance.isSome {
            self.appearance = appearance
        } else {
            self.appearance = KSFilterAppearance()
        }
        
        super.init(nibName: nil, bundle: nil)
        setup()
    }
    // 子类实现
    func layoutContentV() {
        
    }
 
    
    func setup() {
        
        
        self.view.backgroundColor = .clear
        self.view.layer.masksToBounds = true
        self.view.isUserInteractionEnabled = true
        let gr = UITapGestureRecognizer(target: self, action: #selector(close))
        gr.numberOfTapsRequired = 1
        let gr2 = UITapGestureRecognizer(target: self, action: #selector(close))
        gr2.numberOfTapsRequired = 1
        view.addSubview(topCover)
        (topCover).addGestureRecognizer(gr)
        view.addSubview(bottomCover)
        bottomCover.addGestureRecognizer(gr2)
        topCover.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: startY)
        bottomCover.frame = CGRect(x: 0, y: startY, width: KSGlobal.screenW, height: KSGlobal.screenH - startY)

        tableAndConfirmV = UIView()
        tableAndConfirmV.backgroundColor = .white
        bottomCover.addSubview(tableAndConfirmV)
       layoutContentV()
        
//  todo   写搜索弹出 自适应高度
       
        
        
        tableView = UITableView(frame: CGRect.zero,style: .grouped)
       
        tableView!.register(KSFilterCell.self, forCellReuseIdentifier: KSFilterCell.identifier)
        tableView!.register(KSFilter2Cell.self, forCellReuseIdentifier: KSFilter2Cell.identifier)

        tableView!.backgroundColor = .white
        tableView!.separatorStyle = .none
        tableView!.rowHeight = UITableView.automaticDimension
        tableView!.estimatedRowHeight = 44
        tableView!.alpha = 1
        tableView!.delegate = self
        tableView!.dataSource = self
        tableView!.tableFooterView = UIView()
        
        tableAndConfirmV.addSubview(tableView!)
        tableView!.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-60)
        }
        
        tableAndConfirmV.addSubview(reset)
        tableAndConfirmV.addSubview(confirm)
        
        if self.appearance.fType == .searchAndReset ||  self.appearance.fType == .modify {
            if self.appearance.fType == .searchAndReset {
                 confirm.setTitle("查询", for: .normal)
                   reset.setTitle("重置", for: .normal)
            } else {
                confirm.setTitle("确定", for: .normal)
                   reset.setTitle("取消", for: .normal)
            }
     
             reset.layer.cornerRadius = self.appearance.cornerRadius
             reset.snp.makeConstraints { make in
                 make.bottom.equalToSuperview().offset(-20)
                make.width.equalTo(120)
                make.height.equalTo(35)
                make.right.equalTo(tableAndConfirmV.snp.centerX).offset(-10)
            }
            confirm.layer.cornerRadius = self.appearance.cornerRadius
             confirm.snp.makeConstraints { make in
                 make.bottom.equalToSuperview().offset(-20)
                make.width.equalTo(120)
                make.height.equalTo(35)
                make.left.equalTo(tableAndConfirmV.snp.centerX).offset(10)
            }
        } else {
            reset.isHidden = true
            confirm.setTitle("查询", for: .normal)
            confirm.layer.cornerRadius = self.appearance.cornerRadius
             confirm.snp.makeConstraints { make in
                 make.bottom.equalToSuperview().offset(-20)
                make.width.equalTo(280)
                make.height.equalTo(35)
                 make.centerX.equalToSuperview()
            }
        }
        
        
        // 重置
        reset.addTouchUpInSideAction { _ in
            if self.appearance.fType == .searchAndReset {
                self.setFilterDefaultV()
                self.tableView!.reloadData()
                if let clo = self.resetClosure {
                    clo()
                }
            } else {
                self.close()
            }
         }
        
        confirm.addTouchUpInSideAction { _ in
            for x in 0..<self.fContentArr.count {
                
                let theoneArr = self.templateFilter.filter{$0.field_nm == self.fContentArr[x].param}
                 
                if let theone = theoneArr.first {
                    
                    let theConWidget = self.fContentArr[x]
                    
                    if theone.field_type == TemplateType.input.rawValue  {
                        self.filterDic.updateValue(theConWidget.inputStr, forKey: theone.field_nm.unwrap)
                        
                    } else if theone.field_type == TemplateType.localSelect.rawValue {
                        let select_dataArr = theone.select_data.unwrap.components(separatedBy: ",")
                        var numArr = [(String,String)]()
                        for i in 0..<select_dataArr.count {
                            let pre = select_dataArr[i].preChar(char: ":").unwrap
                            let suf = select_dataArr[i].sufChar(char: ":").unwrap
                            numArr.append((pre,suf))
                        }
                        let numArrUtil = KVArrayUtil(arr: numArr)
                        guard  let backarr = theone.selectDataBack else {
                            KSToast("\(theone.field_nm.unwrap)-回填有误")
                            return
                        }
                        guard  theConWidget.dataArr.isSome else {
                            KSToast("\(theConWidget.param)-下拉选数据源有误")
                            return
                        }
                        let ss = theConWidget.dataArr!.filter{ $0.ks_selected }
                        if ss.count > 0 {
                            self.filterDic.updateValue(numArrUtil.getK(v: ss.first!.title), forKey: backarr.idBack.unwrap)
                            self.filterDic.updateValue(ss.first!.title, forKey: backarr.nmBack.unwrap)
                        } else {
                            self.filterDic.updateValue("", forKey: backarr.idBack.unwrap)
                            self.filterDic.updateValue("", forKey: backarr.nmBack.unwrap)

                        }
                        
                        
                    } else if theone.field_type == TemplateType.baselovtree.rawValue {
                        // 他自己的事件里处理了
                    } else if  theone.field_type == TemplateType.date.rawValue ||
                                theone.field_type == TemplateType.month.rawValue ||
                                theone.field_type == TemplateType.datetime.rawValue{
                        
                        self.filterDic.updateValue(theConWidget.inputStr, forKey: theone.field_nm.unwrap)
                        
                    }
                }
                 
            }
        
            
            
            if let clo = self.confirmClosure {
                clo(self.fContentArr)
            }
        }
     
     }
    
    func reloadDataAndTable() {
        for i in 0..<self.fContentArr.count {
            
            if let val = self.filterDic[self.fContentArr[i].param] {
                self.fContentArr[i].inputStr = val
            }
        }
        
        self.tableView?.reloadData()
    }
    //MARK: -- 显示筛选器
    func showFilterV() {
        
        // 筛选随着点击的位置变化
        self.appearance.bgHeight = self.ajustBgHeight(arr: self.fContentArr.filter{$0.isUserShow})
        
        
        // 获取赋值过的值
        for i in 0..<fContentArr.count {
            let oneix = fContentArr[i]
            if let val  = filterDic[oneix.param] {
                fContentArr[i].inputStr = val
            }
    
        }
        
         
        self.layoutContentV()
      
        if self.view.superview.isSome {
            self.close()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
//                if let kwindow =  RouterUtils.currentTopViewController() {
//                    kwindow.present_FullScreen(to:self)
//                }
                self.present()
            }
            
        } else {
            self.present()
//            if let kwindow =  RouterUtils.currentTopViewController() {
//               
//                kwindow.present_FullScreen(to:self)
//            }
        }
    }
    func ajustBgHeight(arr:[SlideContent]) -> CGFloat {
        
        
       
        var hhh = 0
                for item in arr {
                    if item.type == .singleSelect || item.type == .multiSelect {
                        
                        let numofR =  getLocalSelectNumOfR(item.dataArr!)
                        let column = item.dataArr!.count / numofR
                        let singleColumnH = 36
                        var finalH = column * singleColumnH
                        if finalH < 110 {
                            finalH = 110
                        }
                        hhh += finalH
                    } else {
                        hhh += 110
                    }
                }
        
        
        
        
        var hh = CGFloat(hhh) + 60 // 60是底部按钮的高度
        // 给底部留一点背景
        if hh > (KSGlobal.screenH - 128 - 100) {
            hh = (KSGlobal.screenH - 128 - 100)
        }
        return hh
    }
    // 专门设置 日期的附加字段
    func setAppearanceInfodic(infoDic:[String:String]) {
        self.appearance.infoDic = infoDic
    }
    // 子类实现
//    override func willMove(toSuperview newSuperview: UIView?) {
//      
//        
//    }
    // 子类实现
    @objc func close(){
      
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.fContentArr.filter{$0.isUserShow}.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let one = self.fContentArr.filter{$0.isUserShow}[section]
        if one.open.isSome {
            if one.open! {
                if one.type == .singleSelect || one.type == .multiSelect {
                    KSLog("rowcount")
                    KSLog(one.dataArr!.count)
                    KSLog(one.numberOfRow)

                    
                    var rowcount = one.dataArr!.count / one.numberOfRow
                    //有余数，再加一行
                    if one.dataArr!.count % one.numberOfRow != 0 {
                        rowcount += 1
                    }
                    KSLog(rowcount)
                    return rowcount
                } else {
                    return 1
                }
            } else {
                return 0
            }
       
            
        } else {
           return 1
        }
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let theone =  self.fContentArr.filter{$0.isUserShow}[section]
        
        var realIndex = 0
        if let indx = self.fContentArr.getIndexFor({ onex in
            theone.param == onex.param
        }) {
            realIndex = indx
        }
        
        let contentVWidth = KSGlobal.screenW
        let bg = UIView(frame: CGRect(x:0,y:0,width: contentVWidth,height: 30))
        
        
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [realIndex,theone] _ in
            if theone.open.isSome {
               
                    self.fContentArr[realIndex].open = !theone.open!
                    let set = IndexSet(integer:section)
                    tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
               
             
            }
            
        }
        
        bg.addGestureRecognizer(tap)
        
        
        let lab = UILabel(frame: CGRect(x:10,y:0,width: contentVWidth - 10,height: 30))
        lab.font = UIFont.boldSystemFont(ofSize: 16)
        lab.text = theone.title
        
        if theone.disabled {
            lab.textColor = UIColor.lightGray
        } else {
            lab.textColor = UIColor.black
        }
        
        
        
        
        bg.addSubview(lab)
        
        if theone.type == .multiSelect {
            let allBtn = UIButton(frame: CGRect(x:contentVWidth - 70,y:0,width: 40,height: 30))
            allBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            
            let selectCount = theone.dataArr!.filter { $0.ks_selected }
            if selectCount.count == theone.dataArr!.count {
                allBtn.setTitleColor(Theme.primaryColor(), for: .normal)
            } else {
                allBtn.setTitleColor(.lightGray, for: .normal)
            }
            allBtn.setTitle("全部", for: .normal)
            allBtn.addTouchUpInSideAction { _ in
                
                let selectCount = theone.dataArr!.filter { $0.ks_selected }
                if selectCount.count == theone.dataArr!.count {
                    
                    self.fContentArr[realIndex].dataArr =  theone.dataArr!.compactMap({ one -> SeString in
                        var newone = one
                        newone.ks_selected = false
                        return newone
                    })
                    
                } else {
                    self.fContentArr[realIndex].dataArr =  theone.dataArr!.compactMap({ one -> SeString in
                        var newone = one
                        newone.ks_selected = true
                        return newone
                    })
                }
                
                
                
                self.tableView!.reloadData()
                
            }
            bg.addSubview(allBtn)
        }
        
        
        
        if theone.open.isSome {
            let img = UIImageView(image: UIImage(named: theone.open! ? "filter_up" : "filter_down"))
            img.frame = CGRect(x:contentVWidth - 20,y:12,width: 12,height: 8)
            bg.addSubview(img)
        } else {
            
        }
        
        
        return bg
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        let theone =  self.fContentArr.filter{$0.isUserShow}[indexPath.section]
        
        var realIndex = 0
        if let indx = self.fContentArr.getIndexFor({ onex in
            (theone.param == onex.param) && (theone.title == onex.title)
        }) {
            realIndex = indx
        }
        
        
        
 
        if theone.type == .singleSelect || theone.type == .multiSelect {
             guard let cell = tableView.dequeueReusableCell(withIdentifier: KSFilter2Cell.identifier, for: indexPath) as? KSFilter2Cell else {
                fatalError()
            }
            cell.numberOfRow = theone.numberOfRow
            
            KSLog("检测--")
            KSLog("--\(indexPath.row)")
            KSLog("--\(theone.numberOfRow)")
            let start =  indexPath.row * theone.numberOfRow
            if theone.dataArr!.count - start >= theone.numberOfRow {
                let arrRange = Array(theone.dataArr![start..<(start + theone.numberOfRow)])
                KSLog("11")

                KSLog(arrRange)
                cell.titles = arrRange
            } else {
                let yu = theone.dataArr!.count % theone.numberOfRow
                 let arrRange = Array(theone.dataArr![start..<(start + yu)])
                KSLog("22")
                KSLog(arrRange)
                 cell.titles = arrRange
            }
            cell.btnClosure = { [indexPath,theone] tag in
                let indexx = indexPath.row * theone.numberOfRow + tag
               
                
                if theone.type == .singleSelect {
                    for y in 0..<theone.dataArr!.count {
                        self.fContentArr[realIndex].dataArr![y].ks_selected = false
                    }
                    self.fContentArr[realIndex].dataArr![indexx].ks_selected = true
                    
                    
                    if let clo = theone.singleSelctClo {
                        clo(indexx,theone.dataArr![indexx].title)
                    }
                    
                } else {
                    self.fContentArr[realIndex].dataArr![indexx].ks_selected = !theone.dataArr![indexx].ks_selected
                }
                self.tableView!.reloadData()
            }

            return cell
        } else {
            // 量少，不复用，防止串数据
            //        guard let cell = tableView.dequeueReusableCell(withIdentifier: SlideCell.identifier, for: indexPath) as? SlideCell else {
            //            fatalError()
            //        }
            let cell = KSFilterCell(style:UITableViewCell.CellStyle.default, reuseIdentifier: KSFilterCell.identifier)
            
            cell.model = theone
            cell.setborderColor(color: self.appearance.borderColor)
            cell.multiItemClosure = { [indexPath] tag in
                self.fContentArr[realIndex].dataArr![tag].ks_selected = !theone.dataArr![tag].ks_selected
                self.tableView!.reloadData()
            }
            cell.singleItemClosure = { [indexPath] oldtag,newtag in
                if let old = oldtag {
                    self.fContentArr[realIndex].dataArr![old].ks_selected = false
                }
                self.fContentArr[realIndex].dataArr![newtag].ks_selected = true

            }
            cell.dateClosure = { tag in
                if tag == 1 {
                    // 结束日期
                    let max:String? = theone.endDate.isEmpty ? nil : theone.endDate
                    self.showDateSelect( RouterUtils.currentTopViewController()!,self.appearance.infoDic,maxDate: max) { (str) in
                        
                        self.fContentArr[realIndex].startDate = str
                        
                        
                        let set = IndexSet(integer:indexPath.section)
                        tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
                    }
                } else {
                    // 开始日期
                    let min:String? = theone.startDate.isEmpty ? nil : theone.startDate
                    
                    self.showDateSelect( RouterUtils.currentTopViewController()!,self.appearance.infoDic,minDate:min) { (str) in
                        
                        self.fContentArr[realIndex].endDate = str
                        
                        
                        let set = IndexSet(integer:indexPath.section)
                        tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
                    }
                }
                
                
                
                
            }
            cell.textFClosure = { str in
                self.fContentArr[realIndex].inputStr = str
            }
            cell.btnFieldClosure = {
                if let clo = self.fContentArr[realIndex].actionClo {
                    clo(indexPath.section)
                }
            }
            cell.minMoneyClosure = { str in
                self.fContentArr[realIndex].minMoney = str
            }
            cell.maxMoneyClosure = { str in
                self.fContentArr[realIndex].maxMoney = str
            }
            return cell
        }

    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 初始化  重置
    func setFilterDefaultV() {
        
        if self.fContentArr.count == self.fContentArr.filter({$0.isUserShow}).count {
            // 重置所有，初始化状态
            
            let pageArr = templateFilter.filter { $0.field_nm == "page" }
            if pageArr.count > 0 {
                self.default_page = Int(pageArr.first!.default_value.unwrap) ?? 1
            }
            let sizeArr = templateFilter.filter { $0.field_nm == "size" }
            if sizeArr.count > 0 {
                self.default_size = Int(sizeArr.first!.default_value.unwrap) ?? KSGlobal.pageSize
            }
            self.page = self.default_page
            
            // 有模块，优先用模块初始化，然后在用固定的记录原始组件初始化
            if templateFilter.count > 0 {
                // 模板数组 转 控件数组
                self.fContentArr = temp2Fcontent(showTFilter: templateFilter.filter{$0.isFilterShow == "1"})
            } else {
                self.fContentArr = ori_arr
            }

            
            self.filterDic.removeAll()
            // 模板数组 转 字典
            for item in self.templateFilter {
               
                let bData = oneTemp2bannerData(item)
                
                filterDic.updateValue(bData.content.unwrap, forKey: bData.param.unwrap)
            }
                filterDic.updateValue("\(self.page)", forKey: "page")
                filterDic.updateValue("\(self.default_size)", forKey: "size")
           
            
        } else {
            //重置单个
            
//            步骤
//            1 -  找到当前显示的 fcontentarr的单个控件
//            2 - 找到控件对应的模板
//            3 - 模板的值 填给  控件显示
//            4 - 更新持有值的字典
//            
           
 
         
        
            if let indx = fContentArr.getIndexFor({ onex in
                onex.isUserShow
            }) {
                if let tempindex = templateFilter.getIndexFor({ onetemp in
                    onetemp.field_nm == fContentArr[indx].param
                }) {
                   
                    let thisTModel = templateFilter[tempindex]
                    self.fContentArr[indx] = temp2Fcontent(showTFilter: [thisTModel]).first!

                    
                     
                    let bData = oneTemp2bannerData(thisTModel)

                    filterDic[fContentArr[indx].param] = bData.content
                    
                    // 单个的重置，要检索回填，自己回填的值都需要重置
                    
                    //            步骤
                    //            1 - 找到控件对应的模板
                    //            2 - 更新持有值的字典
                    //
                    if thisTModel.lovBackFillArr.count > 0 {
                        
                        let arrJoin = thisTModel.lovBackFillArr.compactMap{$0.sufChar(char: ":").unwrap}.joined(separator: ",")
                        
                            for xxy in templateFilter {
                                if arrJoin.contains(xxy.field_nm.unwrap) {
                                    let bData = oneTemp2bannerData(xxy)
                                    filterDic.updateValue(bData.content.unwrap, forKey: bData.param.unwrap)
                                }
                            }
                            
                       
                    }
                    if thisTModel.selectDataBack.isSome {
                        
                        let arrJoin = thisTModel.selectDataBack!.idBack.unwrap + "," + thisTModel.selectDataBack!.nmBack.unwrap
                        
                            for xxy in templateFilter {
                                if arrJoin.contains(xxy.field_nm.unwrap) {
                                    let bData = oneTemp2bannerData(xxy)
                                    filterDic.updateValue(bData.content.unwrap, forKey: bData.param.unwrap)
                                }
                            }
                            
                       
                    }
                    if thisTModel.field_type == TemplateType.proCityDistrict.rawValue {
                        
                        self.filterDic["s_province_id"] = ""
                        self.filterDic["s_city_id"] = ""
                        self.filterDic["s_county_id"] = ""

                        self.filterDic["s_province_nm"] = ""
                        self.filterDic["s_city_nm"] = ""
                        self.filterDic["s_county_nm"] = ""
                        
                    }
                    
                }
              
            }
            
        }
       
        
        self.reloadDataAndTable()
    }
    // 从一个模板获取相关的值
    func oneTemp2bannerData(_ item:TemplateModel) -> BannerData {
        let pre = item.field_nm.unwrap
        var suf = item.default_value.unwrap
        
        //            1:当天,2:当月第一天;3:前30天;4:前60天;5:前90天
        if item.field_type.unwrap == TemplateType.date.rawValue {
            suf = dateId2Value(item.date_default_value.unwrap)
            // 增加自定义日期情况下的兼容,from: http://59.59.58.36:3316/zentao/task-view-23998.html
            if suf.count == 0 && item.date_default_value?.components(separatedBy: "-").count ?? 0 > 0 {
                suf = item.date_default_value.unwrap
            }
            
        } else if item.field_type.unwrap == TemplateType.datetime.rawValue{
            switch item.date_time_default_value.unwrap {
            case "1":
                suf = Date.nowTimeToSecond
            default:
                break
            }
        } else if item.field_type.unwrap == TemplateType.month.rawValue {
            
            if item.month_default_value.unwrap == "" {
                suf = ""
            } else {
                suf = Date.preMonths(intTran(item.month_default_value))
            }
             
        } else if item.field_type.unwrap == TemplateType.localSelect.rawValue {
            
            
//            let arr = showTFilter[x].select_data.unwrap.components(separatedBy: ",")
//            var numArr = [(String,String)]()
//            for i in 0..<arr.count {
//                let pre = arr[i].preChar(char: ":").unwrap
//                let suf = arr[i].sufChar(char: ":").unwrap
//                numArr.append((pre,suf))
//            }
//            let numArrUtil = KVArrayUtil(arr: numArr)
//            
//            let  sL = SlideContent(param:onexx.field_nm.unwrap,type:.singleSelect, title: showTFilter[x].field_annotation.unwrap,dataArr: numArrUtil.arr.map{ SeString(title: $0.1, ks_selected: false) }, numberOfRow: 3, open: true)
//            newConArr.append(sL)
            
            
        } else {
            
            suf = getDolVal(suf,rootTemp: rootTemp).0
        }
        return BannerData(param: item.field_nm.unwrap,title: item.field_annotation.unwrap,content: suf)
    }
    //MARK: 从模板造筛选的数据源
    func temp2Fcontent(showTFilter:[TemplateModel]) -> [SlideContent] {
        var newConArr = [SlideContent]()
        for x in 0..<showTFilter.count {
            let onexx = showTFilter[x]
            let disabled = onexx.isEditEnable == "0"
            if onexx.field_type == TemplateType.input.rawValue ||
                onexx.field_type == TemplateType.number.rawValue ||
                onexx.field_type == TemplateType.integer.rawValue ||
                onexx.field_type == TemplateType.number2.rawValue {
                let sL = SlideContent(param:onexx.field_nm.unwrap,type:.singleInput,title: onexx.field_annotation.unwrap,disabled: disabled, inputStr: showTFilter[x].default_value.unwrap)
                
                newConArr.append(sL)
                
            } else if onexx.field_type == TemplateType.baselovtree.rawValue {
                
                let dfstr = getDolVal(showTFilter[x].default_value.unwrap,rootTemp: rootTemp).0
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: onexx.field_annotation.unwrap,disabled: disabled,inputStr: dfstr) { cuIndex in
                    
                    if onexx.is_multichoice == "1" {
                        
                        
                        TempHelper.shared.temp_selectPigFarmerMulti(currentNms: [USERINFO.zOrgNm.unwrap]) { [unowned self] (arr) in
                            
                            
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                
                                var vvvArr = [String]()
                                for yItem in arr {
                                    vvvArr.append(any2Str(getValueByKey(obj: yItem, key: pre)))
                                }
                                
                                KSLog("\(suf)---多选赋值\(vvvArr.joined(separator: ","))")
                                self.filterDic[suf] = vvvArr.joined(separator: ",")
                            }
                            
                            self.reloadDataAndTable()
                        }
                    } else {
                        TempHelper.shared.temp_selectPigFarmer(currentNm: USERINFO.zOrgNm.unwrap) { [unowned self] (one) in
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                let vvv = any2Str(getValueByKey(obj: one, key: pre))
                                
                                KSLog("\(suf)---单选赋值\(vvv)")
                                
                                self.filterDic[suf] = vvv
                            }
                            self.reloadDataAndTable()
                        }
                    }
                    
                    
                    
                    
                }
                
                newConArr.append(sL)
                
            } else if onexx.field_type == TemplateType.companylovtree.rawValue {
                
                let dfstr = getDolVal(showTFilter[x].default_value.unwrap,rootTemp: rootTemp).0
                 
                
                var companyTreeParam = ""
                let dsArr = onexx.grmmarArr.filter{ $0.contains(GrammarType.setCompanyTreeParam.rawValue) }
                if dsArr.count == 1 {
                    let arrrr = getKeyPara(dsArr.first!)
                    if arrrr.count == 2 {
                        companyTreeParam = arrrr[1]
                    }
                }
                
                
                
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: showTFilter[x].field_annotation.unwrap,disabled: disabled,inputStr: dfstr) { cuIndex in
                    
                    if onexx.is_multichoice == "1" {
                        
                        TempHelper.shared.temp_selectOrg(type: .multi,param: companyTreeParam) { nodes in
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                
                                
                                
                                var vvvArr = [String]()
                                for yItem in nodes {
                                    vvvArr.append(any2Str(getValueByKey(obj: yItem, key: pre)))
                                }
                                
                                self.filterDic[suf] = vvvArr.joined(separator: ",")
                                
                                
                            }
                            
                            self.reloadDataAndTable()
                        }
                        
                        
                    
                    } else {
                        
                        TempHelper.shared.temp_selectOrg(type: .single,param: companyTreeParam) { nodes in
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                let vvv = any2Str(getValueByKey(obj: nodes.first!, key: pre))
                                self.filterDic[suf] = vvv
                            }
                            self.reloadDataAndTable()
                        }
                 
                    }
                    
                    
                    
                }
                
                newConArr.append(sL)
                
            } else if onexx.field_type == TemplateType.tree.rawValue {
            
                
                let dfstr = getDolVal(showTFilter[x].default_value.unwrap,rootTemp: rootTemp).0
                
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: showTFilter[x].field_annotation.unwrap,disabled: disabled,inputStr: dfstr) { cuIndex in
                    
                    if onexx.is_multichoice == "1" {
                
                        
                        commonTree(type:.multi, onexx: onexx) { nodes in
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                
                                
                                
                                var vvvArr = [String]()
                                for yItem in nodes {
                                    let vx = any2Str(yItem.dic[pre])
                                    vvvArr.append(vx)
                                }
                                
                                
                                self.filterDic[suf] = vvvArr.joined(separator: ",")
                                
                                
                            }
                            self.reloadDataAndTable()
                        }
                        
                        
                        
                  
                        
                    } else {
                        
                        commonTree(type:.single, onexx: onexx) { nodes in
                            for item in onexx.lovBackFillArr {
                                let pre = item.preChar(char: ":").unwrap.camelName
                                let suf = item.sufChar(char: ":").unwrap
                                let vvv = any2Str(nodes.first!.dic[pre])
                                 self.filterDic[suf] = vvv
                            }
                            self.reloadDataAndTable()
                        }
                   
                    }
                 
                }
                
                newConArr.append(sL)
                
                
              
              
                    
              
            } else if onexx.field_type == TemplateType.lov.rawValue {
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: showTFilter[x].field_annotation.unwrap,disabled: disabled,inputStr: "") { cuIndex in
                    
                    
                    var pathDic = url2PathDic(mainDic: self.filterDic,arr: onexx.pathHandler.comPa)
                    
                    
                    let keyPa = onexx.pathHandler.spePa.filter{ $0.contains("keyword") }
                    let showSearch:Bool = (keyPa.count > 0)
                    let sizePa = onexx.pathHandler.spePa.filter{ $0.contains("size") }
                    
                    let vc = KSSingleSelectNetUtil(searchType:showSearch ? .barAndScan : .none)
                    vc.title = "选择"
                    if sizePa.count > 0,intTran(sizePa.first!.sufChar(char: "=")) > 0 {
                        vc.size = intTran(sizePa.first!.sufChar(char: "="))
                    } else {
                        vc.size = 0 // 0为不分页
                    }
                    vc.kSSingleSelectNetNetwork = { page,size,keyword in
                        if showSearch {
                            for ii in 0..<keyPa.count {
                                pathDic.updateValue(keyword, forKey: keyPa[ii].preChar(char: "=").unwrap)
                            }
                        }
                        if size != 0 {
                            pathDic.updateValue("\(page)", forKey: "page")
                            pathDic.updateValue("\(size)", forKey: "size")
                        }
                        KSNetwork.shared.doRequest(API.temp(.path(path: onexx.pathHandler.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                            if data.flag == TRUE {
                                if self.page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:data.infoDicArr)
                                
                            } else {
                                KSToast(data.errorCombine.unwrap)
                            }
                        }
                    }
                    vc.kSSingleSelectNetShowCell = { cell,model in
                        
                        var contArr = [(String,String?)]()
                        
                        
                        
                        for item in onexx.lovShowArr {
                            let pre = item.preChar(char: ":").unwrap
                            let suf = item.sufChar(char: ":").unwrap
                            contArr.append((suf,any2Str((model as! [String:Any])[pre])))
                        }
                        
                        cell.setDataSource(contentArr: contArr)
                        
                        
                    }
                    vc.backClosure = { model in
                        
                        for item in onexx.lovBackFillArr {
                            let pre = item.preChar(char: ":").unwrap
                            let suf = item.sufChar(char: ":").unwrap
                            self.filterDic[suf] = any2Str((model as! [String:Any])[pre])
                            
                        }
                       
                        self.reloadDataAndTable()
                    }
                    
                    let nav = BaseNavigationController()
                    nav.viewControllers = [vc]
                    let topViewController = RouterUtils.currentTopViewController()!

                    topViewController.present_FullScreen(to: nav)
                    
                }
                newConArr.append(sL)
            } else if showTFilter[x].field_type == TemplateType.proCityDistrict.rawValue {
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: showTFilter[x].field_annotation.unwrap,disabled: disabled,inputStr: "") { cuIndex in
                    
                 
                    
                    let nav = BaseNavigationController()
                     let vc = ProvinceCityNetVC()
                    vc.tripleSelectClosure = { province,city,district in
                        
                        
                        self.filterDic["s_province_id"] = province?.id_key
                        self.filterDic["s_city_id"] = city?.id_key
                        self.filterDic["s_county_id"] = district?.id_key

                        self.filterDic["s_province_nm"] = province?.canton_nm
                        self.filterDic["s_city_nm"] = city?.canton_nm
                        self.filterDic["s_county_nm"] = district?.canton_nm
                        
             
                        
                        self.reloadDataAndTable()
                    }
         
                    nav.viewControllers = [vc]
                    RouterUtils.currentTopViewController()!.present_FullScreen(to: nav)
                }
                newConArr.append(sL)
                
                
                
                
                
                
                
                
                
                
            
            } else if  showTFilter[x].field_type == TemplateType.date.rawValue {
                
                let ddd = dateId2Value(showTFilter[x].date_default_value.unwrap)
                
                let   sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: onexx.field_annotation.unwrap,inputStr: ddd,actionClo: { cuIndex in
                    
                    let topViewController = RouterUtils.currentTopViewController()!

                    TempHelper.shared.showTempDate(vc:topViewController,onexx: onexx) { str in
//                        self.fContentArr[cuIndex].inputStr = str
//                        self.tableView!.reloadData()
//                        
                        self.filterDic[onexx.field_nm.unwrap] = str

                        self.reloadDataAndTable()
                    }
                    
                    
                    
                })
                newConArr.append(sL)
                
                
                
            } else if  showTFilter[x].field_type == TemplateType.month.rawValue {
                var ddd = ""
                if showTFilter[x].month_default_value.unwrap == "" {
                    ddd = ""
                } else {
                    ddd = Date.preMonths(intTran(showTFilter[x].month_default_value))
                }
           
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: showTFilter[x].field_annotation.unwrap,disabled: disabled,inputStr: ddd,actionClo: { cuIndex in
                    
                    let view = KSSelectMonthView()
                    view.fetchData = { month in
                        
                        
                        self.filterDic[onexx.field_nm.unwrap] = month

                        self.reloadDataAndTable()
                        
//                        self.fContentArr[cuIndex].inputStr = month
//                        self.tableView!.reloadData()
                    }
                    view.show()
                    
                    
                })
                newConArr.append(sL)
                
                
            } else if  showTFilter[x].field_type == TemplateType.datetime.rawValue {
                var ddd = ""
                switch showTFilter[x].date_time_default_value.unwrap {
                case "1":
                    ddd = Date.nowTimeToSecond
                default:
                    break
                }
                let   sL = SlideContent(param:onexx.field_nm.unwrap,type: .actionClo, title: onexx.field_annotation.unwrap,inputStr: ddd,actionClo: { cuIndex in
                    
                    TempHelper.shared.showDateTime { str in
                        
                        self.filterDic[onexx.field_nm.unwrap] = str

                        self.reloadDataAndTable()
                        
//                        self.fContentArr[cuIndex].inputStr = str
//                        self.tableView!.reloadData()
                    }
                    
                })
                newConArr.append(sL)
                
                
                
            } else if showTFilter[x].field_type == TemplateType.localSelect.rawValue {
                let arr = showTFilter[x].select_data.unwrap.components(separatedBy: ",")
                var numArr = [(String,String)]()
                for i in 0..<arr.count {
                    let pre = arr[i].preChar(char: ":").unwrap
                    let suf = arr[i].sufChar(char: ":").unwrap
                    numArr.append((pre,suf))
                }
                let numArrUtil = KVArrayUtil(arr: numArr)
                
                var finalArr = [SeString]()
                let defVal = showTFilter[x].default_value.unwrap
                
              
                for item in numArrUtil.arr {
                    var selectStatus = defVal.contains(item.1)
                   let changeItem = SeString(title: item.1, ks_selected: selectStatus)
                    finalArr.append(changeItem)
                }
              
                let numofR = getLocalSelectNumOfR(finalArr)
                
                let  sL = SlideContent(param:onexx.field_nm.unwrap,type:.singleSelect, title: showTFilter[x].field_annotation.unwrap,dataArr: finalArr, numberOfRow: numofR, open: true)
                newConArr.append(sL)
            } else {
                KSToast("过滤条件\(showTFilter[x].field_type.unwrap),暂不支持")
            }
            
        }
        return newConArr
    }
    func getLocalSelectNumOfR(_ arr:[SeString]) -> Int {
        var maxValueLength = 0
        for item in arr {
            if item.title.count > maxValueLength {
                maxValueLength = item.title.count
            }
        }
        var numofR = 3
        if maxValueLength > 5 {
            numofR = 2
        } else if maxValueLength > 9 {
            numofR = 1
        }
        return numofR
    }
 
    func present() {
    
        let currentVC = RouterUtils.currentTopViewController()!
        self.modalPresentationStyle = .overFullScreen
        currentVC.present(self, animated: false, completion: nil)
    }
}
extension KSBaseFilterV:UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.tableView!.endEditing(true)
     }
}

func convertToKeyWindowFrame(view: UIView) -> CGRect? {
    guard let keyWindow = UIApplication.shared.connectedScenes
        .compactMap({ $0 as? UIWindowScene })
        .flatMap({ $0.windows })
        .first(where: { $0.isKeyWindow }) else {
            return nil
        }
    
    var convertedFrame = view.bounds
    var targetView: UIView? = view
    
    while let superview = targetView?.superview {
        // 如果是 UIScrollView，则减去 contentOffset
        if let scrollView = superview as? UIScrollView {
            convertedFrame.origin.x -= scrollView.contentOffset.x
            convertedFrame.origin.y -= scrollView.contentOffset.y
        }
        
        convertedFrame = targetView?.convert(convertedFrame, to: superview) ?? .zero
        targetView = superview
        
        // 如果到达 keyWindow，停止转换
        if targetView === keyWindow {
            break
        }
    }
    
    return keyWindow.convert(convertedFrame, from: targetView)
}
